package com.gg;

import com.gg.domain.Chapter;
import com.gg.domain.Content;
import com.gg.service.IBookService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@Controller
@RequestMapping("/book/chapter")
public class ChapterController extends BaseController {
    @Autowired
    IBookService bookService;
    String prefix = "book/chapter";
    @GetMapping()
    public String chapters(@RequestParam int book_id,Model model) {
        model.addAttribute("book_id",book_id);
        return prefix+"/chapter";
    }
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam int book_id) {

        return getDataTable(bookService.getAllChapterByBookId(book_id));
    }
    @GetMapping("/update/{id}")
    public String edit(@PathVariable String id,Model model) {
        String [] temp = id.split("_");
        int book_id = Integer.parseInt(temp[0]);
        int chapter_id = Integer.parseInt(temp[1]);
        Chapter chapter = bookService.getChapter(book_id,chapter_id);
        model.addAttribute("chapter",chapter);
        return prefix+"/edit";
    }
    @PostMapping("/update")
    @ResponseBody
    public AjaxResult saveEdit(Chapter chapter) {
        return toAjax(bookService.updateChapter(chapter));
    }

    @GetMapping("/add")
    public String add(@RequestParam int book_id,Model model) {
        model.addAttribute("book_id",book_id);
        return prefix+"/add";
    }
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult saveAdd(Chapter chapter) {
        return toAjax(bookService.createChapter(chapter));
    }

    @GetMapping("/updateContent")
    public String updateContent(@RequestParam int book_id,int chapter_id,Model model) {
        Content content =
                Optional.ofNullable(bookService.getContent(book_id,chapter_id))
                .orElse(new Content(book_id,chapter_id,""));

        model.addAttribute("content",content);

        return prefix+"/edit_content";

    }
    @PostMapping("/updateContent")
    @ResponseBody
    public AjaxResult ajaxUpdateContent(Content content) {

        return toAjax(bookService.createOrUpdateContent(content));
    }

}
